from django.contrib.auth import authenticate
from django.shortcuts import render
from django.views import View
import logging

logger = logging.getLogger('django')
from lovehome_pro.utils.checkid import check
from django_redis import get_redis_connection
from django.http import JsonResponse
import random, json
from celery_tasks.msm.tasks import ccp_send_sms_code
from lovehome_pro.utils.Loginmixin import LoginMixin
from xyuzi.models import User, House, Order


# Create your views here.
class MessageView(View):
    '''短信验证码'''

    def post(self, request):

        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        uuid = json_dict.get('id')
        text_client = json_dict.get('text')

        # 避免频繁发送短信验证码
        redis_conn = get_redis_connection('verify_code')
        # 进入函数后, 先获取存储在 redis 中的数据
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 查看数据是否存在, 如果存在, 说明60s没过, 返回
        if send_flag:
            return JsonResponse({'errno': '400',
                                 'errmsg': '发送短信过于频繁'})

        # 校验参数
        if not all([text_client, uuid]):
            return JsonResponse({'errno': '400',
                                 'errmsg': '缺少必传参数'})

        # 提取图形验证码
        text_server = redis_conn.get('img_%s' % uuid)

        if text_server is None:
            # 图形验证码过期或者不存在
            return JsonResponse({'errno': '400',
                                 'errmsg': '图形验证码失效'})

        try:
            redis_conn.delete('img_%s' % uuid)

        except Exception as e:
            logger.error(e)

        text_server = text_server.decode()
        # 转小写后比较
        if text_client.lower() != text_server.lower():
            return JsonResponse({'errno': '400',
                                 'errmsg': '输入图形验证码有误'})

        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)

        logger.info(sms_code)

        # 创建管道对象:
        pl = redis_conn.pipeline()

        # 保存短信验证码
        # 短信验证码有效期，单位：300秒
        pl.setex('sms_%s' % mobile, 300, sms_code)

        # 设置过期时间
        pl.setex('send_flag_%s' % mobile, 60, 1)

        # 执行管道:
        pl.execute()

        # 添加celery抛出任务提醒
        ccp_send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return JsonResponse({'errno': '0',
                             'errmsg': '发送成功'})


class RealNameView(LoginMixin, View):
    '''实名认证'''

    def post(self, request):
        # 接收参数
        dict = json.loads(request.body.decode())
        real_name = dict.get('real_name')
        id_card = dict.get('id_card')
        # 校验
        if not all([real_name, id_card]):
            return JsonResponse({'errno': '400',
                                 'errmsg': '缺少必传参数'})

        if not check(id_card):
            return JsonResponse(({'code': '400',
                                  'errmsg': '不满足格式要求'}))

        try:
            user = User.objects.filter(id_card=id_card)
            if user:
                return JsonResponse({
                    'code': '400',
                    'errmsg': '已经实名'
                })
        except Exception as e:
            return JsonResponse({
                'code': '400',
                'errmsg': '数据库查询失败'
            })

        try:
            User.objects.filter(id=request.user.id).update(id_card=id_card, real_name=real_name)
        except Exception as e:
            return JsonResponse({
                'code': '400',
                'errmsg': '保存数据失败'
            })
        # 返回
        return JsonResponse({'errno': '0',
                             'errmsg': '认证信息保存成功'})

    def get(self, request):
        id_card = request.user.id_card
        real_name = request.user.real_name
        if not all([id_card, real_name]):
            id_card = None
            real_name = None
        return JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': {
                'id_card': id_card,
                'real_name': real_name
            }
        })

class OrderListView(View):
    pass
